package com.hospital.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hospital.domain.pojo.AdmissionApplication;
import com.hospital.domain.utils.Result;
import com.hospital.domain.utils.UserContext;
import com.hospital.mapper.AdmissionApplicationMapper;
import com.hospital.service.AdmissionApplicationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Random;

@Service
public class AdmissionApplicationServiceImpl implements AdmissionApplicationService {

    @Autowired
    private AdmissionApplicationMapper admissionApplicationMapper;

    @Autowired
    private com.hospital.service.OrdersService ordersService;

    @Override
    public Result<String> submitApplication(AdmissionApplication application) {
        try {
            // 生成申请编号
            String aNumber = generateApplicationNumber();
            application.setANumber(aNumber);
            application.setAApplyTime(LocalDateTime.now());
            application.setAState(0); // 待审批
            int result = admissionApplicationMapper.insert(application);
            if (result > 0) {
                return Result.ok("住院申请提交成功，申请编号：" + aNumber);
            } else {
                return Result.error("住院申请提交失败");
            }
        } catch (Exception e) {
            return Result.error("系统异常：" + e.getMessage());
        }
    }

    @Override
    public Result<List<AdmissionApplication>> getPatientApplications(Integer pId) {
        try {
            List<AdmissionApplication> applications = admissionApplicationMapper.selectByPatient(pId);
            return Result.ok(applications);
        } catch (Exception e) {
            return Result.error("查询失败：" + e.getMessage());
        }
    }

    @Override
    public Result<List<AdmissionApplication>> getPendingApplications() {
        try {
            List<AdmissionApplication> applications = admissionApplicationMapper.selectByState(0);
            return Result.ok(applications);
        } catch (Exception e) {
            return Result.error("查询失败：" + e.getMessage());
        }
    }

    @Override
    public Result<List<AdmissionApplication>> getDepartmentApplications(Integer depId, Integer state) {
        try {
            List<AdmissionApplication> applications = admissionApplicationMapper.selectByDepartmentAndState(depId, state);
            return Result.ok(applications);
        } catch (Exception e) {
            return Result.error("查询失败：" + e.getMessage());
        }
    }

    @Override
    public Result<String> approveApplication(Integer aId, Integer approveDoctor) {
        try {
            AdmissionApplication application = admissionApplicationMapper.selectById(aId);
            if (application == null) {
                return Result.error("申请不存在");
            }
            
            application.setAState(1); // 已批准
            application.setAApproveTime(LocalDateTime.now());
            application.setAApproveDoctor(approveDoctor);
            
            int result = admissionApplicationMapper.updateById(application);
            if (result > 0) {
                try {
                    // 创建住院押金订单（统一5000元）
                    Integer pId = application.getPId();
                    ordersService.createDepositOrder(pId, aId);
                } catch (Exception ignored) {}
                return Result.ok("申请已批准");
            } else {
                return Result.error("批准失败");
            }
        } catch (Exception e) {
            return Result.error("系统异常：" + e.getMessage());
        }
    }

    @Override
    public Result<String> rejectApplication(Integer aId, Integer approveDoctor, String rejectReason) {
        try {
            AdmissionApplication application = admissionApplicationMapper.selectById(aId);
            if (application == null) {
                return Result.error("申请不存在");
            }
            
            application.setAState(2); // 已拒绝
            application.setAApproveTime(LocalDateTime.now());
            application.setAApproveDoctor(approveDoctor);
            application.setARejectReason(rejectReason);
            
            int result = admissionApplicationMapper.updateById(application);
            if (result > 0) {
                return Result.ok("申请已拒绝");
            } else {
                return Result.error("拒绝失败");
            }
        } catch (Exception e) {
            return Result.error("系统异常：" + e.getMessage());
        }
    }

    @Override
    public Result<AdmissionApplication> getApplicationById(Integer aId) {
        try {
            AdmissionApplication application = admissionApplicationMapper.selectById(aId);
            if (application != null) {
                return Result.ok(application);
            } else {
                return Result.error("申请不存在");
            }
        } catch (Exception e) {
            return Result.error("查询失败：" + e.getMessage());
        }
    }

    @Override
    public Result<List<AdmissionApplication>> getAllApplications() {
        try {
            List<AdmissionApplication> applications = admissionApplicationMapper.selectList(null);
            return Result.ok(applications);
        } catch (Exception e) {
            return Result.error("查询失败：" + e.getMessage());
        }
    }

    // 新增：根据医生ID查询
    @Override
    public Result<List<AdmissionApplication>> getDoctorApplications(Integer dId) {
        try {
            List<AdmissionApplication> list = admissionApplicationMapper.selectByDoctor(dId);
            return Result.ok(list);
        } catch (Exception e) {
            return Result.error("查询失败：" + e.getMessage());
        }
    }

    // 新增：根据医生ID和状态查询
    @Override
    public Result<List<AdmissionApplication>> getDoctorApplicationsByState(Integer dId, Integer state) {
        try {
            List<AdmissionApplication> list = admissionApplicationMapper.selectByDoctorAndState(dId, state);
            return Result.ok(list);
        } catch (Exception e) {
            return Result.error("查询失败：" + e.getMessage());
        }
    }

    private String generateApplicationNumber() {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd");
        String dateStr = LocalDateTime.now().format(formatter);
        Random random = new Random();
        int randomNum = random.nextInt(900000) + 100000; // 6位随机数
        return "ADM" + dateStr + randomNum;
    }
}
